/**
* v-copyText 复制文本内容
* Copyright (c) 2022 ruoyi
*/

import type { Directive, DirectiveBinding } from 'vue';

interface CopyOptions {
  target?: HTMLElement;
}

type CopyModifiers = Partial<Record<string, boolean>>;

export default {
  beforeMount(el: HTMLElement, binding: DirectiveBinding) {
    const handleCallback = () => {
      // 处理可能的修饰符
      let valueToCopy = binding.value;
      if (binding.modifiers?.trim && typeof valueToCopy === 'string') {
        valueToCopy = valueToCopy.trim();
      }
      
      const success = copyTextToClipboard(valueToCopy);
      
      // 执行回调
      if (typeof binding.arg === 'string' && binding.arg.startsWith('callback')) {
        (binding.value as Function)?.(success, valueToCopy);
      } else if (typeof binding.value === 'function') {
        binding.value(success, valueToCopy);
      }
    };

    el.addEventListener('click', handleCallback);
    (el as any).$destroyCopy = () => el.removeEventListener('click', handleCallback);
  },
  
  unmounted(el: HTMLElement) {
    (el as any).$destroyCopy?.();
  }
} as Directive;

/**
 * 复制文本到剪贴板
 * @param input 要复制的文本
 * @returns 是否成功复制
 */
function copyTextToClipboard(input: string | number | boolean): boolean {
  const text = String(input);
  const element = document.createElement('textarea');
  const previouslyFocusedElement = document.activeElement as HTMLElement | null;

  // 设置文本区域内容
  element.value = text;
  element.setAttribute('readonly', '');
  
  // 样式设置
  Object.assign(element.style, {
    contain: 'strict',
    position: 'absolute',
    left: '-9999px',
    fontSize: '12pt'
  });

  document.body.appendChild(element);
  
  // 选择文本并复制
  element.select();
  element.setSelectionRange(0, text.length); // 兼容iOS

  let isSuccess = false;
  try {
    isSuccess = document.execCommand('copy');
  } catch (e) {
    console.warn('Copy failed:', e);
  }

  // 清理DOM
  document.body.removeChild(element);
  
  // 恢复选区
  const selection = document.getSelection();
  if (selection && selection.rangeCount > 0) {
    selection.removeAllRanges();
  }

  // 恢复焦点
  previouslyFocusedElement?.focus();

  return isSuccess;
}

// 可选的现代API实现方案
async function modernCopy(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (err) {
    console.warn('Modern copy failed:', err);
    return false;
  }
}